const { Router } = require('express')
const router = new Router()

// 引入权限验证
const rolesPermission = require('../../../utils/validateRole/rolesPermission')
// 引入解密token
const {verifyToken} = require('../../../utils/verification')
// 引入轮播图模型
const RotationModel = require('../../../model/rotation')

router.get('/showRotation', function (request, response) {

    const option = {
        bidPrice: 1,
        launchStartTime: 1,
        launchEndTime: 1,
        isShow: 1,
        rotationPic: 1,
        goodsId: 1,
        chargeNum: 1
    }

    const validate = {
        permitRoles: [],
        secret: request.get('permission')
    }

    // 当角色是admin时
    validate.permitRoles = ['admin']
    if (rolesPermission(validate)){
        return oprate({},option,response, request)
    }
    // 当是商城中的商户人员时
    validate.permitRoles = ['boss','manager','server']
    if (rolesPermission(validate)){
        const { _id } = request.query
        // 当本人是老板时
        validate.permitRoles = ['boss']
        if (rolesPermission(validate)){
            return oprate({
                    bidderId: _id
                },option,response)
        }else {
            // 本人不是老板
            const { bossId } = request.query

            return  oprate({
                    bidderId: bossId
                },option,response,request)
        }
    }

})

function oprate(findData,option, response, request){
    const data = {
        code: '200',
        data: 'error',
        msg: '查看直通车失败'
    }
    const pageInfo = {}
    if (request.query.pageInfo){
        pageInfo['page'] = request.query.pageInfo.page? parseInt(request.query.pageInfo.page): 1
        pageInfo['limit'] = request.query.pageInfo.limit?parseInt(request.query.pageInfo.limit):10
    }
    RotationModel.count(findData,function (err,doc) {
        if (err) return response.json(data)

        data.count = doc

        RotationModel.find(findData,option).sort({bidPrice:-1}).skip( (pageInfo.page - 1) * pageInfo.limit).limit(pageInfo.limit).exec(function (err,doc) {
            if (err) return response.json(data)

            data.data = doc
            data.msg = '查看直通车成功'

            response.json(data)
        })
    })
}

module.exports = router
